<?php

namespace App\Console;

use App\Events\DestroyOrder;
use App\Events\SalesNumber;
use App\Integral;
use App\Order;
use App\OrderAction;
use App\TeamFollow;
use App\TeamFound;
use App\User;
use App\UserPersonnel;
use Carbon\Carbon;
use EasyWeChat\Factory;
use Illuminate\Console\Scheduling\Schedule;
use Illuminate\Foundation\Console\Kernel as ConsoleKernel;
use Illuminate\Support\Facades\Log;

class Kernel extends ConsoleKernel
{
    /**
     * The Artisan commands provided by your application.
     *
     * @var array
     */
    protected $commands = [
        //
    ];

    /**
     * Define the application's command schedule.
     *
     * @param  \Illuminate\Console\Scheduling\Schedule $schedule
     * @return void
     */
    protected function schedule(Schedule $schedule)
    {
        // $schedule->command('inspire')
        //          ->hourly();
        $schedule->call(function () {
            $this->teamActivityReFund();
        })->dailyAt('1:00');

        $schedule->call(function () {
            $this->vipcancel();
        })->dailyAt('2:00');

        $schedule->call(function () {
            $this->destroyOrder();
        })->everyThirtyMinutes();
    }

    /**
     * Register the commands for the application.
     *
     * @return void
     */
    protected function commands()
    {
        $this->load(__DIR__ . '/Commands');

        require base_path('routes/console.php');
    }

    protected function teamActivityReFund()
    {
        // 已到时的团购活动
        $founds = TeamFound::where('status', 'ACTIVE')
            ->where('ended_at', '<', Carbon::now())
            ->get();
        // 查询已到时的团购活动，进行退款
        if (count($founds) > 0) {
            foreach ($founds as $found) {
                if ($found->join >= $found->needer) {
                    $found->status = 'SUCCESS';
                    $found->save();
                } else {
                    foreach ($found->follows as $follow) {
                        $order = $follow->order;
                        // 微信公众号支付退款
                        if ($order && $order->pay_status === 1 && $order->pay_code === 'JSAPI') {
                            $payment = Factory::payment(config('wechat.payment.default'));
                            $result = $payment->refund->byOutTradeNumber($order->order_sn, $order->order_sn, $order->order_amount * 100, $order->order_amount * 100, [
                                // 可在此处传入其他参数，详细参数见微信支付文档
                                'refund_desc' => '拼团失败，系统自动退款',
                            ]);
                            Log::info($result);
                            if ($result['return_code'] == 'SUCCESS' && $result['result_code'] == 'SUCCESS') {
                                $order->pay_status = 3;
                                $order->status = 'FINISHED';
                                $order->save();

                                // 创建订单日志
                                OrderAction::newAction($order, ['action' => '退款成功', 'note' => '拼团失败，系统自动退款', 'user_id' => 0]);
                            }
                        }
                        // 删除未支付的订单
                        if ($order && $order->pay_status === 0) {
                            // 统计商品销量及库存
                            event(new SalesNumber($order, -1));
                            // 删除订单事件
                            event(new DestroyOrder($order));
                            $order->delete();
                        }
                    }
                    $count = TeamFollow::where('team_found_id', $found->id)
                        ->whereHas('order', function ($query) {
                            return $query->where('pay_status', 1);
                        })->count();

                    if ($count === 0) {
                        $found->status = 'FAIL';
                        $found->save();
                    }
                }
            }
        }
    }

    protected function destroyOrder()
    {
        $orders = Order::where('pay_status', 0)
            ->where('created_at', '<', Carbon::now()->subMinute(30))
            ->get();
        // 删除商品, 并计算商品的库存
        foreach ($orders as $order) {
            //统计商品销量及库存
            event(new SalesNumber($order, -1));
            //删除商品处理
            event(new DestroyOrder($order));
            if ($order->qingbi_price > 0) {
                $user = User::find($order->user_id);
                $user->qingbi = $user->qingbi + intval($order->qingbi_price);
                Integral::create(['user_id' => $user->id, 'number' => $order->qingbi_price, 'type' => 1, 'category' => 2, 'description' => '订单支付超市，返还轻币']);
                $user->save();
            }
            $order->delete();
        }
    }

    /**
     * 过期vip vip到期时间清0
     */
    protected function vipcancel()
    {
        $time = strtotime(date('Y-m-d'));
        $userAll = UserPersonnel::all();
        foreach ($userAll as $v) {
            if ($v->vip_over_time <= $time) {
                $user = UserPersonnel::find($v->id);
                $user->vip_over_time = 0;
                $user->save();
            }
        }
    }

}
